package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RequestMappingHandlerMapping handlerMapping;


    @Override
    public void load() {
        List<String> allResource = permissionMapper.selectAllResource();
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        Collection<HandlerMethod> methods = handlerMethods.values();
        for (HandlerMethod method : methods) {
            RequiresPermissions methodAnnotation = method.getMethodAnnotation(RequiresPermissions.class);
            if (methodAnnotation != null) {
                String[] resources = methodAnnotation.value();
                if (!allResource.contains(resources[0])) {
                    Permission permission = new Permission();
                    permission.setName(resources[1]);
                    permission.setResource(resources[0]);
                    permissionMapper.load(permission);
                }
            }
        }

    }

    @Override
    public Permission selectByPrimaryKey(Long id) {

        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        Integer total = permissionMapper.query4Count(qo);
        if (total == 0) {
            return PageResult.PAGERESULT_EMPTY;
        }
        return new PageResult(total, permissionMapper.query4List(qo));
    }

    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        return permissionMapper.getPermissionsByRoleId(roleId);
    }
}
